package com.wz.dhs.controller.system;

import com.wz.dhs.constant.UserConstants;
import com.wz.dhs.dto.user.RoleQueryDTO;
import com.wz.dhs.exception.BusinessException;
import com.wz.dhs.model.UserContextHolder;
import com.wz.dhs.model.common.PageInfo;
import com.wz.dhs.model.common.Result;
import com.wz.dhs.model.ruoyi.TreeSelect;
import com.wz.dhs.po.user.SysMenu;
import com.wz.dhs.po.user.SysRole;
import com.wz.dhs.service.base.SystemService;
import com.wz.dhs.utils.StringUtils;
import com.wz.dhs.vo.base.RouterVo;
import com.wz.dhs.vo.login.UserInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@Validated
@AllArgsConstructor
@RequestMapping("/")
@Slf4j
@Api(tags = "系统相关")
public class SystemController {

    @Autowired
    private SystemService systemService;

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation("路由信息")
    @GetMapping("getRouters")
    public Result<List<RouterVo>> getRouters() {
        Long userId = UserContextHolder.getUserId();
        List<RouterVo> menus = systemService.selectMenuTreeByUserId(userId);
        return Result.data(menus);
    }

    @PostMapping("/info")
    @ApiOperation("查看用户信息")
    public Result<UserInfoVO> userInfo() {
        return Result.data(systemService.userInfo());
    }


    @ApiOperation("菜单列表")
    @GetMapping("/system/menu/list")
    public Result menulist(SysMenu menu) {
        List<SysMenu> menus = systemService.selectMenuList(menu);
        return Result.data(menus);
    }

    @ApiOperation("查询角色信息")
    @GetMapping("/role")
    public Result<PageInfo<SysRole>> list(RoleQueryDTO role) {
        return Result.data(systemService.selectRoleList(role));
    }


    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping(value = "/system/menu/{menuId}")
    public Result getInfo(@PathVariable Long menuId) {
        return Result.data(systemService.selectMenuById(menuId));
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @PutMapping("/system/menu")
    public Result<String> edit(@Validated @RequestBody SysMenu menu) {
        if (!systemService.checkMenuNameUnique(menu)) {
            throw new BusinessException("10023", "修改菜单" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            throw new BusinessException("10023", "修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            throw new BusinessException("10023", "修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(UserContextHolder.getUserInfo().getUsername());
        systemService.updateMenu(menu);
        return Result.success("修改成功");
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @DeleteMapping("/system/menu/{menuId}")
    public Result<String> remove(@PathVariable("menuId") Long menuId) {
        if (systemService.hasChildByMenuId(menuId)) {
            throw new BusinessException("10023", "存在子菜单,不允许删除");
        }
        if (systemService.checkMenuExistRole(menuId)) {
            throw new BusinessException("10023", "菜单已分配,不允许删除");
        }
        systemService.deleteMenuById(menuId);
        return Result.success("删除成功");
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @PostMapping("/system/menu")
    public Result<String> add(@Validated @RequestBody SysMenu menu)
    {
        if (!systemService.checkMenuNameUnique(menu))
        {
            throw new BusinessException("10023", "新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
        {
            throw new BusinessException("10023", "新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(UserContextHolder.getUserInfo().getUsername());
        systemService.insertMenu(menu);
        return Result.success("新增成功");
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/system/menu/treeselect")
    public Result<List<TreeSelect>> treeselect(SysMenu menu)
    {
        List<SysMenu> menus = systemService.selectMenuList(menu, UserContextHolder.getUserId());
        return Result.data(systemService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/system/menu/roleMenuTreeselect/{roleId}")
    public Result<HashMap> roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysMenu> menus = systemService.selectMenuList(UserContextHolder.getUserId());
        HashMap map = new HashMap();
        map.put("checkedKeys", systemService.selectMenuListByRoleId(roleId));
        map.put("menus", systemService.buildMenuTreeSelect(menus));
        return Result.data(map);
    }



}
